#!/usr/local/bin/ruby
# -*- coding: utf-8 -*-

require 'batch_common'

print "\n"
print "batch_create_item\n"
print "start "+Time.now.strftime("%Y-%m-%d %H:%M:%S")+"\n"

db = getDB()

site = Array.new
sql = "
SELECT
     id
   , host
   , (SELECT SUM(msec)/COUNT(*) FROM check_result r WHERE r.site_id = s.id AND r.status_code = '200') AS avg
   , (SELECT size FROM check_result r WHERE r.site_id = s.id AND r.size <> 0 ORDER BY r.id DESC LIMIT 1) AS size
   , (SELECT status_code FROM check_result r WHERE r.site_id = s.id ORDER BY r.id DESC LIMIT 1) AS status_code
FROM
     site s
ORDER BY 
     id
"

r = db.query(sql);
r.each_hash do |r|
  id = r['id'];
  host = r['host'];
  kbyte = r['size'].to_i / 1024.0
  site.push({:id=>id, :host=>host, :avg=>r['avg'], :kbyte=>kbyte, :status_code=>r['status_code']});
 
  list = Array.new
  y_max = 0;
  y_min = 99999999;
  res = query_check_result(db, id, '1 day');
  res.each_hash{|row|
    y_max = [y_max, Integer(row['msec'])].max
    y_min = [y_min, Integer(row['msec'])].min
    list.push([row['date'],row['msec']])
  }
  y_max = convYMax( y_max );
  
  list_m = Array.new
  y_max_m = 0
  y_min_m = 99999999
  res = query_check_result(db, id, '1 month');
  res.each_hash{|row|
    y_max_m = [y_max_m, Integer(row['msec'])].max
    y_min_m = [y_min_m, Integer(row['msec'])].min
    list_m.push([row['date'],row['msec']])
  }
  
  title = host
  str = Erubis::EscapedEruby.load_file('/home/code4/public/app/tmpl/site_detl.rhtml').result(binding())
  put_detl(id, str);
end

str = Erubis::EscapedEruby.load_file('/home/code4/public/app/tmpl/index.rhtml').result(binding())
put_index(str)

print "end "+Time.now.strftime("%Y-%m-%d %H:%M:%S")+"\n"
